package com.ask.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.ask.dto.QuestionParam;
import com.ask.service.QuestionService;

import com.ask.utils.ResultBundle;
import com.ask.utils.ResultListBundle;
import com.ask.utils.ResultBundleBuilder;
import com.ask.utils.MD5Util;
import com.ask.utils.CommonConstants;
import com.ask.utils.ErrorCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value="", tags = {"提问管理"})
@RestController
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private ResultBundleBuilder bundleBuilder;

    @RequestMapping("/hello")
    public String index() {
        return "hello world!";
    }

    @RequestMapping("/foo")
    public String foo(String foo) {
        return "hello "+foo+"!";
    }

    @RequestMapping(value="/ask", method=RequestMethod.POST)
    public ResultBundle<Integer> ask(HttpServletRequest request,
                                     @RequestBody QuestionParam questionParam) {
        String sign = request.getHeader("sign");
        // 请求头中有sign，是C端请求，判断sign
        if (StringUtils.isNotEmpty(sign)) {
            StringBuffer origin = new StringBuffer();
//            origin.append(CommonConstants.KEY_MD5).append("channel:").append("&").append("timestamp:")
//                    .append(timestamp).append(CommonConstants.KEY_MD5);
//            if (sign.equals(MD5Util.getEncrypted(origin.toString()))) {
            if(true){
                questionService.ask(questionParam);
                return bundleBuilder.bundle(null, () -> (Integer) (1));
            }
        }

        return new ResultListBundle<>(null, 0, false, ErrorCode.REQUEST_INVALID.getMessage());
    }

    @RequestMapping(value="/update", method=RequestMethod.POST)
    public ResultBundle<Integer> update(HttpServletRequest request,
                                     @RequestBody QuestionParam questionParam) {
        String sign = request.getHeader("sign");
        // 请求头中有sign，是C端请求，判断sign
        if (StringUtils.isNotEmpty(sign)) {
            StringBuffer origin = new StringBuffer();
//            origin.append(CommonConstants.KEY_MD5).append("channel:").append("&").append("timestamp:")
//                    .append(timestamp).append(CommonConstants.KEY_MD5);
//            if (sign.equals(MD5Util.getEncrypted(origin.toString()))) {
            if(true){
                questionService.update(questionParam);
                return bundleBuilder.bundle(null, () -> (Integer) (1));
            }
        }

        return new ResultListBundle<>(null, 0, false, ErrorCode.REQUEST_INVALID.getMessage());
    }
}